#encoding:utf-8

'''
data=2017/1/17 下午3:12
__author__='binpo',
author_email='binpocn@163.com',
'''

from grapheneapi.grapheneclient import GrapheneClient
from grapheneapi.grapheneapi import GrapheneAPI
from grapheneexchange.exchange import GrapheneExchange
from grapheneapi.graphenewsrpc import GrapheneWebsocketRPC
from models import QueryRecord,Exchange
import json

e_chat_id='1.2.328095'

class Config():
    wallet_host = "localhost"
    wallet_port = 8089
    wallet_user = "etao"
    wallet_password = "aa6vuCw84BxQa3uT"
    witness_url = "ws://127.0.0.1:5909"
    witness_user = "etao"
    witness_password = "aa6vuCw84BxQa3uT"
    account = "etao"

graphene = GrapheneClient(Config)
graphene.rpc.unlock('aa6vuCw84BxQa3uT')

record = QueryRecord.select().where(QueryRecord.record_type=='etao').get()
start = record.start
limit = record.limit
ws = GrapheneWebsocketRPC("ws://127.0.0.1:5909","etao","aa6vuCw84BxQa3uT")
# wc.get_account('etao')

def insert_new_exchange(data):

    {'memo': '\u8fd9\u662f\u4e00\u4e2a\u6d4b\u8bd5\u4fe1\u606f',
     'description': 'Transfer 0.001 EDC from binpocn163.com to etao -- Memo: \u8fd9\u662f\u4e00\u4e2a\u6d4b\u8bd5\u4fe1\u606f   (Fee: 0.001 EDC)',
     'op': {'op_in_trx': 0,
            'id': '1.11.6402623',
            'block_num': 2625327,
            'virtual_op': 62046,
            'result': [0, {}],
            'trx_in_block': 6,
            'op': [0, {'memo': {'to': 'EDC64XJ3pfFKkEp9r63hbr5S5S6ZeUAVUcJYUm3RSfyVA7kuAraU9',
                                                   'from': 'EDC85A1XUwBc6qSP9hSfHf6uusd3rHBkVfUFmXv8qS4YiaQ1bDE3A',
                                                   'nonce': '380088287852123',
                                                   'message': '51bf32f8c5d84355dac037dd556a9c57c6a9750db1631d139cde99fe42175b17'},
                                          'amount': {'asset_id': '1.3.1', 'amount': 1},
                       'to': '1.2.328095',
                                          'from': '1.2.321340', 'extensions': [],
                                          'fee': {'asset_id': '1.3.1', 'amount': 1}
                       }
                   ]
            }
     }

    exist_exchange = Exchange.select().where(Exchange.block_num==data.get('op').get('block_num')).first()
    if exist_exchange:
        return
    exchange = Exchange()
    exchange.echange_type = 'etao'
    exchange.amount = data.get('op').get('op')[1].get('amount').get('amount')
    if not data.get('memo'):
        exchange.status=True
    exchange.app_account =  data.get('memo')
    exchange.session = ''
    exchange.block_num = data.get('op').get('block_num')
    exchange.content = json.dumps(data)
    exchange.save()

data = ws.getFullAccountHistory('etao',start,limit)
if len(data)<limit:
    exchange_list = graphene.rpc.get_account_history("etao", len(data)+1)
    try:
        for exchange in exchange_list:
            insert_new_exchange(exchange)
    except:
        pass
    record.start = start+len(data)
    record.save()
elif len(data)==limit:
    block_num = data[0].get('block_num')
    exchange = Exchange.select().where(Exchange.block_num==block_num).first()
    if exchange:
        pass
    else:
        while True:
            limit = limit + 50
            data = ws.getFullAccountHistory('etao', record.start,limit)
            if len(data)<limit:
                exchange_list = graphene.rpc.get_account_history("etao", len(data) + 1)
                try:
                    for exchange in exchange_list:
                        insert_new_exchange(exchange)
                except:
                    pass
                record.start = record.start+len(data)
                record.save()
                break
            else:
                continue
# dex = GrapheneExchange(Config)
# balances = dex.returnBalances()